/*
 * Written by Dustin striplin
 */

package Actions;

import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;

import javax.swing.AbstractAction;
import javax.swing.JOptionPane;
import javax.swing.JTable;

import org.apache.poi.xwpf.extractor.XWPFWordExtractor;
import org.apache.poi.xwpf.usermodel.XWPFDocument;

import FileParser.FileParser;
import Model.Author;
import Model.Constants;
import Model.Review;
import TableModels.AuthorTemplate;
import View.ManuscriptView;

public class AuthorViewReviews extends AbstractAction{
	JTable table;
	Author author;
	
	/**
	 * Create a AuthorViewReviews actino
	 * @param table The table this action will manipulate
	 * @param author The author object that is logged in
	 */
	public AuthorViewReviews(JTable table, Author author) {
		this.table = table;
		this.author = author;
		this.putValue(NAME, "View Reviews");
		this.putValue(MNEMONIC_KEY, KeyEvent.VK_R);
	}
	
	/**
	 * Opens up a review for each paper the author can see only
	 * if the paper has been accepted or rejected.
	 */
	@Override
	public void actionPerformed(ActionEvent arg0) {
		if(table.getSelectedRow() != -1) {
			//convert to models row index, since the table index changes when it is sorted
			int row = table.convertRowIndexToModel(table.getSelectedRow());
							//check that a decision was made
			if(((AuthorTemplate)table.getModel()).getApproval(row) != Constants.UNDECIDED.getValue()) {  
				ArrayList<Review> links = ((AuthorTemplate)table.getModel()).getReviews(row);//get link
				if(!links.isEmpty()) {
					for(int i = 0; i < links.size(); i++) {
						InputStream stream = FileParser.class.getResourceAsStream(links.get(i).getReviewLink());	//convert to stream
						try { // apache poi documentation  http://poi.apache.org/apidocs/index.html
								XWPFDocument docx = new XWPFDocument(stream);				//parse docx
								XWPFWordExtractor we = new XWPFWordExtractor(docx);			//extract parsed docx
								//System.out.println(we.getText());						
								ManuscriptView scriptWindow = new ManuscriptView();
								scriptWindow.start(we.getText());
				
						} catch (IOException e1) {
							// TODO Auto-generated catch block
							e1.printStackTrace();
						}
						try {
								stream.close();
						} catch (IOException e1) {
							// TODO Auto-generated catch block
							e1.printStackTrace();
						}
					}
				}
			} else {
				JOptionPane.showMessageDialog(null, "A decision has not been made yet");
			}
		}
		
	}
}


/*
		


*/